//
//  MusciDetailViewController.m
//  ToWhere
//
//  Created by dllo on 15/11/22.
//  Copyright © 2015年 www.TE.com. All rights reserved.
//

#import "MusciDetailViewController.h"
#import "MusicDetailCollectionViewCell.h"
#import <MJRefresh.h>
#import "DataAnalysis.h"
#import <SDWebImageManager.h>
#import <UIImageView+WebCache.h>
#import "MusicDetailModel.h"
#import "MusicPlayViewController.h"
#import "SaveTools.h"

@interface MusciDetailViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property(nonatomic, retain) UIView *titleView;

@property(nonatomic, retain) UILabel *titleLabel;

@property(nonatomic, retain) UICollectionView *collectionView;

@property(nonatomic, retain) MJRefreshAutoGifFooter *footer;

@property(nonatomic, assign) NSInteger page;

@property(nonatomic, retain) UIImageView *imageview;

@property(nonatomic, retain) NSMutableArray *musicDatailArray;

@property (nonatomic, retain) UIAlertController *al;

@end

@implementation MusciDetailViewController

- (void)dealloc
{
    [_titleView release];
    [_titleLabel release];
    [_collectionView release];
    [_footer release];
    [_imageview release];
    [_musicDatailArray release];
    [_al release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.page = 1;
    self.musicDatailArray = [NSMutableArray array];
    
    //数据请求
    [self loadData];
    
    //创建CollectionView
    [self createCollectionView];
    
    //创建头视图
    [self createView];
    
    //创建标题
    [self createTitle];
    
}

#pragma mark 创建标题
-(void)createTitle
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,kHeight * 64)];
    [self.view addSubview:self.titleView];
    [self.titleView release];
    [_titleView release];
    
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 130 * kWidth, self.titleView.frame.size.height / 2 - 10 * kHeight, kWidth * 260, kHeight * 30)];
    self.titleLabel.text = self.allModel.name;
    self.titleLabel.textColor = [[UIColor whiteColor]colorWithAlphaComponent:1];
    self.titleLabel.font = [UIFont systemFontOfSize:17 * kWidth];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.titleView addSubview:self.titleLabel];
    [_titleLabel release];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(15 * kWidth, 25 * kHeight, 20 * kWidth, 20 * kHeight);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"Food_back"] forState:UIControlStateNormal];
    [self.titleView addSubview:backBtn];
    [backBtn addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:[UIImage imageNamed:@"Music"] forState:UIControlStateNormal];
    btn.frame = CGRectMake(340 * kWidth, self.titleView.frame.size.height / 2 - 7 * kHeight, 30 * kWidth, 30 * kWidth);
    [self.titleView addSubview:btn];
    [btn addTarget:self action:@selector(playViewAction:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)BackAction:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)playViewAction:(UIButton *)btn
{
    NSString *music = [SaveTools readFromFileName:@"music" andFilePath:NSLibraryDirectory];
    if (music == nil) {
        self.al = [UIAlertController alertControllerWithTitle:nil message:@"还没有你的播放印记哦!" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:self.al animated:YES completion:nil];
        [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(remove) userInfo:nil repeats:YES];
    }
    else
    {
        MusicPlayViewController *player = [MusicPlayViewController shareMusicPlayViewController];
        [self setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:player animated:YES];
        [self setHidesBottomBarWhenPushed:NO];
    }
}
- (void)remove{
    [self.al dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 创建头视图
-(void)createView
{
    self.imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, -220 * kHeight - (1 - kHeight) * 20, self.view.frame.size.width, 220 * kHeight)];
    [self.imageview sd_setImageWithURL:[NSURL URLWithString:self.allModel.pic_640] placeholderImage:[UIImage imageNamed:@"placeHoder"]];
    self.imageview.userInteractionEnabled = YES;
    [self.collectionView addSubview:self.imageview];
    [_imageview release];
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, self.imageview.frame.size.height - 50 * kHeight, self.imageview.frame.size.width, 50 * kHeight)];
    backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [self.imageview addSubview:backView];
    [backView release];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(25 * kWidth, 10 * kHeight, 70 * kWidth, 30 * kHeight);
    [btn setTitle:@"随便听听" forState:UIControlStateNormal];
    btn.layer.cornerRadius = 10 * kWidth;
    btn.titleLabel.font = [UIFont systemFontOfSize:14 * kWidth];
    btn.layer.borderColor = [UIColor greenColor].CGColor;
    btn.backgroundColor = [UIColor colorWithRed:0.913 green:0.945 blue:0.924 alpha:1.000];
    [btn setTitleColor:[UIColor colorWithWhite:0.145 alpha:1.000] forState:UIControlStateNormal];
    [backView addSubview:btn];
    [btn addTarget:self action:@selector(suibianAction:) forControlEvents:UIControlEventTouchUpInside];
    
    NSArray *countArray = @[self.allModel.sound_count, self.allModel.follow_count, self.allModel.share_count];
    NSArray *titleArray = @[@"声音", @"关注", @"分享"];
    for (int i = 0; i < 3; i++) {
        UILabel *countLabel = [[UILabel alloc]initWithFrame:CGRectMake(115 * kWidth + i * 80, 10 * kHeight, 100 * kWidth, 15 * kHeight)];
        countLabel.text = [NSString stringWithFormat:@"%@", countArray[i]];
        countLabel.font = [UIFont systemFontOfSize:13 * kWidth];
        countLabel.textColor = [UIColor whiteColor];
        [backView addSubview:countLabel];
        [countLabel release];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(115 * kWidth + i * 80, 28 * kHeight, 100 * kWidth, 15 * kHeight)];
        titleLabel.text = titleArray[i];
        titleLabel.font = [UIFont systemFontOfSize:13 * kWidth];
        titleLabel.textColor = [UIColor whiteColor];
        [backView addSubview:titleLabel];
        [titleLabel release];
        
        if (i < 2) {
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(175 * kWidth + i * 80, 15 * kHeight, 2 * kWidth, 20 * kHeight)];
            line.backgroundColor = [UIColor whiteColor];
            [backView addSubview:line];
            [line release];
        }
    }
}
//随便听听点击事件
-(void)suibianAction:(UIButton *)btn
{
    [SaveTools saveToFileName:@"music" andFilePath:NSLibraryDirectory andVaule:@"0"];
    NSInteger row = arc4random() % self.musicDatailArray.count;
    MusicPlayViewController *music = [MusicPlayViewController shareMusicPlayViewController];
    music.playListArray = self.musicDatailArray;
    music.row = row;
    music.backImage = [self.musicDatailArray[row] pic_750];
    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:music animated:YES];
}
#pragma mark 创建collectionView
-(void)loadData
{
    [DataAnalysis dataAnalysisGETWithUrlString:[NSString stringWithFormat:@"http://echosystem.kibey.com/channel/info?limit=20&id=%@&list_order=hot&page=%ld", self.allModel.ID,self.page] parameters:nil showHuD:YES hiddenView:nil successfulBlock:^(id responseObject) {
        
        for (NSDictionary *dic in [[[responseObject objectForKey:@"result"] objectForKey:@"data"] objectForKey:@"sounds"]) {
            MusicDetailModel *detailModel = [MusicDetailModel musicDetailWithDictionary:dic];
            [self.musicDatailArray addObject:detailModel];
        }
//        NSLog(@"%@", [NSString stringWithFormat:@"http://echosystem.kibey.com/channel/info?limit=20&id=%@&list_order=hot&page=%ld", self.allModel.ID,self.page]);
        [self.collectionView reloadData];
        [self.collectionView.footer endRefreshing];
       
    } failureBlock:^(NSError *error) {
        NSLog(@"error : %@", error);
    }];
}

-(void)loadMoreData
{
    _page += 1;
    [self loadData];
}

#pragma mark 创建collectionView
-(void)createCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, - 20 * kHeight, self.view.frame.size.width, self.view.frame.size.height + 20 * kHeight) collectionViewLayout:flowLayout];
    self.collectionView.contentInset = UIEdgeInsetsMake(220 * kHeight, 0, 0, 0);
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[MusicDetailCollectionViewCell class] forCellWithReuseIdentifier:@"MusicDetailCollectionViewCell"];
    
    //注册头尾视图
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerView"];
    
    [_collectionView release];
    [flowLayout release];
    
    //下拉加载
    self.footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.collectionView.footer = self.footer;
    
}

//返回行数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.musicDatailArray.count;
}

//返回分区数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//左右间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5 * kWidth;
}

//行间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 5 * kHeight;
}

//items大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.view.frame.size.width / 2 - 9 * kWidth, 200 * kHeight);
}

//内间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5 * kHeight, 5 * kWidth, 5 * kWidth, 5 * kHeight);
}

//头尾视图
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        
        UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        reusableView.backgroundColor = [UIColor whiteColor];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(5 * kWidth, 10 * kHeight, 375 * kWidth, 30 * kHeight)];
        titleLabel.font = [UIFont systemFontOfSize:16];
        titleLabel.backgroundColor = [UIColor whiteColor];
        titleLabel.text = self.allModel.info;
        [reusableView addSubview:titleLabel];
        [titleLabel release];
        
        return reusableView;
    }
    else
    {
        UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerView" forIndexPath:indexPath];
        reusableView.backgroundColor = [UIColor colorWithWhite:0.927 alpha:1.000];
        return reusableView;
    }
}

//返回头视图高
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(self.view.frame.size.width, 40 * kHeight);
}

//尾视图高
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(self.view.frame.size.width, 1 * kHeight);
}

//重用池
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MusicDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MusicDetailCollectionViewCell" forIndexPath:indexPath];
    cell.detailModel = self.musicDatailArray[indexPath.row];
    return cell;
}

//点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MusicPlayViewController *player = [MusicPlayViewController shareMusicPlayViewController];
    player.backImage = [self.musicDatailArray[indexPath.row] pic_750];
    player.playListArray = self.musicDatailArray;
    player.row = indexPath.row;
    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:player animated:YES];
    [SaveTools saveToFileName:@"music" andFilePath:NSLibraryDirectory andVaule:@"0"];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y > -45 && scrollView.contentOffset.y < 800) {
        self.titleView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:scrollView.contentOffset.y / 800];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
